package com.tgjorgoski.sidekicknotes.rtfview.support;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.JTextPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;

import com.tgjorgoski.spellcheck.highlight.*;
import com.tgjorgoski.utils.CalmRunner;
import com.tgjorgoski.window.Session;

public class SpellCheckSupport implements DocumentListener, HighlightParametersChangeListener, PropertyChangeListener {
	CalmRunner calmRunner;
	JTextPane tComponent;
	NodesHighlighter spellCheckHighlighter;
	private Document oldDocument;

	private static SpellCheckSupport instance;
	
	private SpellCheckSupport() {
		super();
	}
	
	public static SpellCheckSupport getInstance() {
		if (instance==null) {
			instance=new SpellCheckSupport();
		}
		return instance;
	}

	public void registerComponent(JTextPane tComponent) {
		this.tComponent=tComponent;
		spellCheckHighlighter=new SpellcheckHighlighter();
		spellCheckHighlighter.addHighlightChangeListener(this);
		tComponent.getDocument().addDocumentListener(this);
		
		//listen for loading of another page, so that we can attach to the new document 
		tComponent.addPropertyChangeListener("page", this);
		oldDocument=tComponent.getDocument();
	}

	
	public void updateHighlights() {
		if (!Session.getHTMLEditor().shouldSpellcheck()) return;
		if (calmRunner==null) {
			calmRunner = new CalmRunner(new Runnable() {
				public void run() {
					HighlightUtil.highlight(tComponent, spellCheckHighlighter);
				}
			}, 1000);
		}
		calmRunner.run();
	}
	
	public void removeHighlights() {
		HighlightUtil.removeHighlights(tComponent, spellCheckHighlighter);
	}

	public void changedUpdate(DocumentEvent e) {
		updateHighlights();
	}

	public void insertUpdate(DocumentEvent e) {
		updateHighlights();
	}

	public void removeUpdate(DocumentEvent e) {
		updateHighlights();
	}

	public void highlightParametersChange(NodesHighlighter highlighter) {
		updateHighlights();
	}

	public void propertyChange(PropertyChangeEvent evt) {
		if (evt.getSource() instanceof JTextComponent) {
			JTextComponent tc = (JTextComponent)evt.getSource();
			switchToNewDocument(tc.getDocument());
		}
	}
	
	public void switchToNewDocument(Document doc) {
		oldDocument.removeDocumentListener(this);
		doc.addDocumentListener(this);
		updateHighlights();
	}
	
}
